import { login, logout, getInfo, getMenu } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, {  resetRouter, sidebarRoutes } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    id:'',
    user:{}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_USER: (state, user) => {
    state.user = user
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        const { id, name, avatar } = data

        commit('SET_USER', data)
        commit('SET_NAME', name)
        // commit('SET_AVATAR', process.env.VUE_APP_BASE_API + "/file/get/" + avatar.name)
        commit('SET_ID', id)
        // getSidebar(id).then(() =>{
        //   router.addRoutes([{ path: '*', redirect: '/404', hidden: true }])
        // } )
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}
async function getSidebar(id) {
  await getMenu({ id, type: 0 }).then(response => {
    const { data } = response
    for (let item of data) {
      let menu = {
        path: item.path,
        name: item.name,
        meta: { title: item.name, icon: item.icon },
        component:(resolve) => require(['@/layout'], resolve),
        redirect: item.redirect ? item.redirect : undefined,
        hidden: item.hidden,
        children: []
      }
      handleChildren(menu, item.children)
      if (item.children === undefined && item.component.length > 0) {
        let child = JSON.parse(JSON.stringify(menu))
        child.children = undefined
        child.component = (resolve) => require(['@/views' + item.component], resolve)
        menu.children.push(child)
        menu.meta = undefined
      }
      sidebarRoutes.push(menu)
    }
    router.addRoutes(sidebarRoutes)
  })
}
function handleChildren(menu, children) {
  if (children===undefined) {
    return
  }
  for (let child of children) {
    let childMenu = {
      path: child.path,
      name: child.name,
      meta: { title: child.name, icon: child.icon },
      component: (resolve) => require(['@/views' + child.component], resolve),
      hidden: child.hidden,
      children: []
    }
    menu.children.push(childMenu)
    handleChildren(childMenu, child.children)
    if (childMenu.children.length < 1) {
      childMenu.children = undefined
    }


  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

